<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>循环全景照片</title>
</head>
<body>
    <div>
        <canvas id="canvas" width="800" height="200"></canvas>
    </div>
    <script>
        var img = new Image();
            img.src = 'https://mdn.mozillademos.org/files/4553/Capitan_Meadows,_Yosemite_National_Park.jpg';
        var CanvasXSize = 800;
        var CanvasYSize = 200;
        var speed = 30; // lower is faster
        var scale = 1.05;
        var y = -4.5; // vertical offset

        // Main program

        var dx = 0.75;
        var imgW;
        var imgH;
        var x = 0;
        var clearX;
        var clearY;
        var ctx;
        ctx = document.getElementById('canvas').getContext('2d');
        img.onload = function(){
            imgW = img.width * scale;
            imgH = img.height * scale;

            if (imgW > CanvasXSize) {
                // image larger than canvas
                x = CanvasXSize - imgW;
            }
            if (imgW > CanvasXSize) {
                // image width larger than canvas
                clearX = imgW;
            } else {
                clearX = CanvasXSize;
            }
            if (imgH > CanvasYSize) {
                // image height larger than canvas
                clearY = imgH;
            } else {
                clearY = CanvasYSize;
            }

            // ctx = document.getElementById('canvas').getContext('2d');

            // return setInterval(draw,speed);
        }

        function draw(){
            window.requestAnimationFrame(draw)
            ctx.clearRect(0, 0, clearX, clearY);
            // if image is <= Canvas Size
            if (imgW <= CanvasXSize) {
                // reset, start from beginning
                if (x > CanvasXSize) {
                    x = -imgW + x;
                }
                // draw additional image1
                if (x > 0) {
                    ctx.drawImage(img, -imgW + x, y, imgW, imgH);
                }
                // draw additional image2
                if (x - imgW > 0) {
                    ctx.drawImage(img, -imgW * 2 + x, y, imgW, imgH);
                }
            }

            // image is > Canvas Size
            else {
                // reset, start from beginning
                if (x > (CanvasXSize)) {
                    x = CanvasXSize - imgW;
                }
                // draw aditional image
                if (x > (CanvasXSize-imgW)) {
                    ctx.drawImage(img, x - imgW + 1, y, imgW, imgH);
                }
            }
            // draw image
            ctx.drawImage(img, x, y,imgW, imgH);
            // amount to move
            x += dx;
        }
        draw()
    </script>
</body>
</html>